from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers

from goods.models import Brand


class BrandsSerializer(serializers.ModelSerializer):
    """
    品牌序列化器
    """
    class Meta:
        model = Brand
        fields = ('id','name','logo','first_letter')

    def create(self, validated_data):
        image_data = validated_data.get('logo')
        client = Fdfs_client(settings.FASTDFS_CONF)
        ret = client.upload_by_buffer(image_data.read())
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        img_url = ret['Remote file_id']
        logo = Brand.objects.create(logo=img_url,first_letter=validated_data['first_letter'],name=validated_data['name'] )

        # 返回图片表对象
        return logo

    def update(self, instance, validated_data):
        # 获取保存的图片数据
        image_data = validated_data.get('logo')
        # 建立FastDFS的链接对象
        client = Fdfs_client(settings.FASTDFS_CONF)
        # 上传图片数据
        res = client.upload_by_buffer(image_data.read())
        # 判断上传状态
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 上传成功 获取返沪爹图片路径信息
        logo_url = res['Remote file_id']

        # 更新图片路径
        instance.logo = logo_url
        instance.name = validated_data['name']
        instance.first_letter = validated_data['first_letter']
        instance.save()
        return instance